"""
其他功能组件
"""

import tkinter as tk
from tkinter import messagebox
import numpy as np
from typing import TYPE_CHECKING

from ..clip_library import ClipLibraryWindow
from ..edge_optimization_dialog import EdgeOptimizationDialog
from ..channel_editor_dialog import ChannelEditorDialog

if TYPE_CHECKING:
    from ..main_window import MainWindow


class OtherFeaturesMixin:
    """其他功能 Mixin 类"""
    
    def add_to_clip_library(self: 'MainWindow'):
        """添加当前选中对象到裁剪库（带边缘优化选择）"""
        if self.current_result is None:
            messagebox.showwarning(
                "警告",
                "请先选择对象！\n\n使用单点或框选模式选择对象后，\n即可添加到裁剪库。",
                parent=self.root
            )
            return
        
        if self.image is None:
            return
        
        # 传入原始mask，让对话框自己处理平滑和边缘优化
        # 这样"原图"选项可以返回真正的原始mask
        original_mask = self.current_result.mask
        
        # 打开边缘优化选择对话框
        def on_optimization_selected(method_key: str, optimized_mask: np.ndarray):
            """边缘优化方法选择回调"""
            # 添加到裁剪库（使用原始图像进行裁剪）
            clip_item = self.clip_manager.add_clip(
                self._get_image_for_clip(),
                optimized_mask,
                score=self.current_result.score
            )
            
            method_name = {
                "original": "原图",
                "feather": "羽化边缘",
                "feather_gaussian": "羽化+高斯模糊",
                "feather_gaussian_stroke": "羽化+高斯+描边",
                "choke": "收缩遮罩",
                "decontaminate": "颜色去溢",
                "choke_decontaminate": "收缩+去溢",
                "guided_filter": "引导滤波",
                "custom_smooth_harden": "自定义调节",
                "gaussian": "高斯模糊"
            }.get(method_key, "未知")
            
            # 选择"原图"时，不显示边缘平滑信息，因为原图选项本身就不应该应用平滑
            if method_key == "original":
                smooth_info = ""
            else:
                smooth_info = " + 边缘平滑" if self.smooth_mask_var.get() else ""
            
            self.update_status(f"已添加到裁剪库: {clip_item.name} (优化方法: {method_name}{smooth_info})")
            
            # 如果裁剪库窗口打开，刷新显示
            if self.clip_library_window and self.clip_library_window.window.winfo_exists():
                self.clip_library_window.refresh()
            
            messagebox.showinfo(
                "成功",
                f"已添加到裁剪库！\n\n"
                f"名称: {clip_item.name}\n"
                f"优化方法: {method_name}{smooth_info}\n"
                f"裁剪库共 {self.clip_manager.get_clip_count()} 项",
                parent=self.root
            )
        
        # 创建边缘优化选择对话框（传入原始图像和原始mask）
        EdgeOptimizationDialog(
            self.root,
            self._get_image_for_clip(),
            original_mask,
            self.image_processor,
            on_select=on_optimization_selected
        )
    
    def open_clip_library(self: 'MainWindow'):
        """打开裁剪库窗口"""
        # 检查窗口是否已打开
        if self.clip_library_window and self.clip_library_window.window.winfo_exists():
            # 窗口已存在，激活它
            self.clip_library_window.window.lift()
            self.clip_library_window.window.focus_force()
            return
        
        # 创建新窗口
        self.clip_library_window = ClipLibraryWindow(
            self.root,
            self.clip_manager,
            on_close=self._on_clip_library_closed
        )
    
    def _on_clip_library_closed(self: 'MainWindow'):
        """裁剪库窗口关闭回调"""
        self.clip_library_window = None
        self.logger.info("裁剪库窗口已关闭")
    
    def open_channel_editor(self: 'MainWindow'):
        """打开RGB通道编辑器"""
        if self.image is None:
            messagebox.showwarning("警告", "请先加载图片！", parent=self.root)
            return
        
        # 创建通道编辑器对话框
        def on_channel_apply(channel_image: np.ndarray, channel_config: dict):
            """通道编辑应用回调"""
            self.logger.info(f"应用通道配置: {channel_config}")
            
            # 替换原图
            self._replace_image_with_channel(channel_image, channel_config)
        
        ChannelEditorDialog(
            self.root,
            self.image,
            on_apply=on_channel_apply
        )

